package com.course.servlet;

import com.course.entity.Course;
import com.course.entity.CourseSelection;
import com.course.entity.Student;
import com.course.service.CourseService;
import com.course.service.CourseSelectionService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@WebServlet("/xuesheng_course_selection")
public class XueshengCourseSelectionServlet extends HttpServlet {
    private final CourseService courseService = new CourseService();
    private final CourseSelectionService courseSelectionService = new CourseSelectionService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String teacherIdParam = request.getParameter("teacherId");
        List<Course> courses;

        if (teacherIdParam != null && !teacherIdParam.trim().isEmpty()) {
            try {
                int teacherId = Integer.parseInt(teacherIdParam);
                courses = courseService.getCoursesByTeacherId(teacherId);
            } catch (NumberFormatException e) {
                // Handle invalid teacherId format, maybe show an error message
                request.setAttribute("errorMessage", "请输入有效的老师ID。");
                courses = courseService.getAllCourses(); // Fallback to all courses
            }
        } else {
            courses = courseService.getAllCourses();
        }

        HttpSession session = request.getSession();
        Student student = (Student) session.getAttribute("student");

        if (student == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }

        List<CourseSelection> studentCourseSelections = courseSelectionService.getStudentCourses(student.getId());

        Map<Integer, String> studentCourseStatusMap = studentCourseSelections.stream()
                .collect(Collectors.toMap(CourseSelection::getCourseId, CourseSelection::getStatus, (oldValue, newValue) -> newValue));

        Map<Integer, Integer> selectedStudentsCountMap = new HashMap<>();
        Map<Integer, Integer> remainingCapacityMap = new HashMap<>();

        for (Course course : courses) {
            int selectedCount = courseSelectionService.getCourseStudents(course.getId()).size();
            selectedStudentsCountMap.put(course.getId(), selectedCount);
            int remainingCapacity = course.getMaxCapacity() - selectedCount;
            remainingCapacityMap.put(course.getId(), remainingCapacity);
        }

        request.setAttribute("courses", courses);
        request.setAttribute("selectedStudentsCountMap", selectedStudentsCountMap);
        request.setAttribute("remainingCapacityMap", remainingCapacityMap);
        request.setAttribute("studentCourseStatusMap", studentCourseStatusMap);
        request.getRequestDispatcher("/student/xuesheng_course_selection.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        HttpSession session = request.getSession();
        Student student = (Student) session.getAttribute("student"); 

        if (student == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }

        int studentId = student.getId();
        int courseId = Integer.parseInt(request.getParameter("courseId"));
        String action = request.getParameter("action"); // 'select' or 'drop'

        String message = null;
        if ("select".equals(action)) {
            String result = courseSelectionService.selectCourse(studentId, courseId);
            if ("SUCCESS".equals(result)) {
                message = "选课成功！";
                request.setAttribute("successMessage", message);
            } else {
                message = "选课失败：";
                switch (result) {
                    case "COURSE_NOT_FOUND":
                        message += "课程不存在。";
                        break;
                    case "ALREADY_SELECTED_BY_ID":
                        message += "您已选过该课程。";
                        break;
                    case "ALREADY_SELECTED_SAME_DESCRIPTION":
                        message += "您已选过相同描述的课程，请勿重复选择。";
                        break;
                    case "COURSE_FULL":
                        message += "课程已满。";
                        break;
                    case "DB_ADD_FAILED":
                        message += "数据库操作失败，请重试。";
                        break;
                    case "DB_UPDATE_FAILED":
                        message += "数据库更新失败，请重试。";
                        break;
                    default:
                        message += "未知错误。";
                        break;
                }
                request.setAttribute("errorMessage", message);
            }
        } else if ("drop".equals(action)) {
            boolean success = courseSelectionService.dropCourse(studentId, courseId);
            if (success) {
                message = "退课成功！";
                request.setAttribute("successMessage", message);
            } else {
                message = "退课失败，请重试。";
                request.setAttribute("errorMessage", message);
            }
        }
        
        doGet(request, response); // Forward back to display page with messages
    }
} 